import 'dart:async';
import 'dart:io';

import 'package:amap_map_fluttify/amap_map_fluttify.dart';
import 'package:boss/common/common.dart';
import 'package:boss/http/api/api.dart';
import 'package:boss/jpush/jpush.dart';
import 'package:boss/router.dart';
import 'package:boss/ui/page/login/model/cache_user.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_crashlytics/firebase_crashlytics.dart';
import 'package:flustars/flustars.dart' as flustars;
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_baidutts/flutter_baidutts.dart';
import 'package:fluwx/fluwx.dart' as fluwx;
import 'package:hi_common/hi_common.dart';
import 'package:package_info/package_info.dart';

import 'channel/baiduSpeech/baidu_speech.dart';
import 'ui/app.dart';
import 'ui/page/index/index_page.dart';
import 'ui/page/login/login_page.dart';
import 'ui/page/splash/splash_page.dart';
import 'package:dio/dio.dart';

Api api;

void main() async {
  runZonedGuarded(() async {
    WidgetsFlutterBinding.ensureInitialized();

    await Firebase.initializeApp();

    //强制竖屏
    await SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp, DeviceOrientation.portraitDown]);

    await flustars.SpUtil.getInstance();

    final isFirst = !flustars.SpUtil.getBool(Constant.spFirst);

    router['/'] = (ctx) => isFirst
        ? SplashPage()
        : CacheUser.usableUser == null
            ? LoginPage()
            : IndexPage();

    final packageInfo = await PackageInfo.fromPlatform();
    Constant.appVersion = packageInfo.version;

    Constant.uuid = await Utils.getUuId('BOSS');

    final dioUtil = DioUtil(Constant.httpServer);
    api = Api(dioUtil.dio, baseUrl: Constant.httpServer);
    dioUtil.dio.interceptors.add(LogInterceptor(
      responseBody: true,
      requestBody: true,
    ));

    final cacheUser = CacheUser.usableUser;

    if (cacheUser != null) {
      TokenInterceptor.token = cacheUser.loginUser.token;
    }

    runApp(GlobalProviderApp());

    initBaiduTTS();

    JPushUtil.instance.init();

    initWx();

    initAMap();

    initBaiduSpeech();

    setCustomErrorPage();
  }, (error, stackTrace) {
    FirebaseCrashlytics.instance.recordError(error, stackTrace);
  });
}

//遮蔽报红的Widget
setCustomErrorPage() {
  ErrorWidget.builder = (FlutterErrorDetails flutterErrorDetails) {
    FirebaseCrashlytics.instance.recordFlutterError(flutterErrorDetails);
    return SizedBox();
  };
}

//设置百度语音识别参数
initBaiduSpeech() {
  BaiduSpeech.instance.setClientConfig(
    apiKey: Constant.baiduApiKey,
    secretKey: Constant.baiduSecretKey,
    appId: Constant.baiduAppId,
  );
}

//初始化高德地图
initAMap() async {
  await AmapService.instance.init(
    iosKey: Constant.amapIosKey,
    androidKey: Constant.amapAndroidKey,
  );
}

initWx() async {
  final status = await fluwx.registerWxApi(appId: Constant.wxAppId, universalLink: Constant.wxUniversalLink);
  print('微信SDK初始化：$status');
}

initBaiduTTS() async {
  final config = {
    'ios': {'appId': '17932105', 'appKey': 'eBVkl20Dg5sCC48BMORQmFyB', 'appSecret': 'LbYoig486aCGodm3QIRMFH0O762UGpRx'},
    'android': {'appId': '17971391', 'appKey': '9HYj2pNPfympXOKkQoXxEbkr', 'appSecret': 'FSewcn92bIsXyrohk8ZPYVOlG37G0ufS'},
  };
  final targetConfig = Platform.isIOS ? config['ios'] : config['android'];

  FlutterBaidutts.instance.init(
    appId: targetConfig['appId'],
    appKey: targetConfig['appKey'],
    appSecret: targetConfig['appSecret'],
  );
}
